var createError = require('http-errors');
var express = require('express');
var path = require('path');
let cors=require("cors")
var cookieParser = require('cookie-parser');
var logger = require('morgan');

//引入路由模块
var indexRouter= require('./routes/index');

var listRouter = require('./routes/list');

var searchRouter = require('./routes/search');

var loginRouter = require('./routes/login');

var personalRouter = require('./routes/personalCenter');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
// 接收post的参数
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// 解决跨域问题
app.use(cors())
app.use(cookieParser());
// 开放静态资源
app.use(express.static(path.join(__dirname, 'public')));
app.use("/upload",express.static(path.join(__dirname, 'uploads')));

// 关于接口的开发 习惯性会加前缀 /api
app.use('/api', indexRouter);
app.use('/api', listRouter);
app.use('/api', searchRouter);
app.use('/api', loginRouter);
app.use('/api', personalRouter);

// 404 error
app.use(function(req, res, next) {
  // next(createError(404));
  res.status(404)
  res.send({
    code:404,
    msg:"404页面不存在"
  })
});

// 500 error 中间件
app.use(function(err, req, res, next) {
    // res.status(500)
    res.send({
      code:500,
      msg:err
    })
});

module.exports = app;
